<?php

namespace app\api\controller;

use app\common\model\Vote as VoteModel;
use app\common\model\Article;
use think\Db;
use think\Exception;

/**
 * 会员收藏
 */
class Vote extends Base
{
    protected $noNeedLogin = [];

    /**
     * 我的收藏
     */
    public function index()
    {
        $vote = new VoteModel;
        $user_id = $this->auth->id;
        $voteList = $vote
            ->alias('c')
            ->where('c.uid', $user_id)
            ->join('article a','a.id=c.aid','left')
            ->order('c.createtime', 'desc')
            ->paginate(10);
        $voteList = $voteList->toArray();

        return $this->success('获取成功', $voteList,200);
    }

    /**
     * 添加收藏
     */
    public function create()
    {
        $type = $this->request->get("type");//1 点赞 2：取消
        $aid = $this->request->get("aid/d");
        $article =  db('article')->where('id',$aid)->find();
        if (!$article) {
            $this->error("未找到指定数据");
        }
        $vote = VoteModel::where([ 'aid' => $aid, 'uid' => $this->auth->id])->find();
        if($type == 1){
            Db::startTrans();
            try {
                if ($vote) {
                    throw new \think\Exception("请勿重复点赞");
                }
                $data = [
                    'uid' => $this->auth->id,
                    'aid'    => $aid,
                ];
                VoteModel::create($data);
                Article::where([ 'id' => $aid])->setInc('likes');
                Db::commit();
            } catch (\think\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                $this->error("点赞失败");
            }
            $info = Article::where([ 'id' => $aid])->field('id,likes')->find();
            $this->success("点赞成功",$info);
        }else{
            Db::startTrans();
            try {
                if (!$vote) {
                    throw new \think\Exception("请勿重复操作");
                }
                $vote->delete();
                Article::where([ 'id' => $aid])->setDec('likes');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error("移除点赞失败");
            }
            $info = Article::where([ 'id' => $aid])->field('id,likes')->find();
            $this->success("移除点赞成功",$info);
        }

    }
}
